//
//  UIImage+Extension.swift
//  SinaWeibo
//
//  Created by 程建 on 16/10/6.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

extension UIImage {
    
    class func snapShotCurrentScreen() -> UIImage {
        
        let window = UIApplication.shared.keyWindow!
        
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.main.scale)
        
        
        //2.将当前的window绘制到上下文中
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
        
        //3.从图片上下文获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //4.关闭图片上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    //等比例压缩图片
    //需要指定宽度或者高度进行压缩
    func scaleImage(width:CGFloat)->UIImage {
        let imageW = self.size.width
        let imageH = self.size.height
        //如果图片本身的宽度的就小于压缩的宽度就直接返回
        if imageW < width {
            
            return self
        }
        //根据宽高比例,计算高度
        let scaleH = imageH / imageW * width
        
        let imageBounds = CGRect(x: 0, y: 0, width: width, height: scaleH)
        
        UIGraphicsBeginImageContextWithOptions(imageBounds.size, false, UIScreen.main.scale)
        self.draw(in: imageBounds)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image!
        
    }
}
